import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.jupiter.api.Test;

import java.io.File;
import java.util.List;

public class Dom4j_ {

    //演示如何加载xml文件
    @Test
    public void loadXML() throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File("src/students.xml"));

    }

    //遍历xml文件中学生信息
    @Test
    public void listXML() throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File("src/students.xml"));
        Element root = document.getRootElement();//已经获得了students根元素
        List<Element> students = root.elements("student");//不能写成students
        for (Element student : students) {
            Element name = student.element("name");
            Element age = student.element("age");
            Element gender = student.element("gender");

            System.out.println("name: " + name.getText()+
                    ", age: " + age.getText()+
                    ", gender: " + gender.getText());
        }
    }

    //指定读取xml文件中学生信息
    @Test
    public void readOneXML() throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File("src/students.xml"));
        Element root = document.getRootElement();//已经获得了students根元素
        List<Element> students = root.elements("student");//不能写成students
        Element student = students.get(0);
        Element name = student.element("name");
        Element age = student.element("age");
        Element gender = student.element("gender");

        System.out.println("name: " + name.getText()+
                ", age: " + age.getText()+
                ", gender: " + gender.getText());

        //还有一些增删改(调用io流)，就是调用document的一些api,有需要的时候自己查一下
    }
}
